<?php
namespace app\tools\controller\base;

use app\common\model\admin\AccountModel;
use app\tools\model\base\MenuNodesModel;
use think\admin\Controller;
use think\admin\extend\DataExtend;
use think\admin\helper\QueryHelper;
use think\admin\model\SystemAuth;
use think\admin\model\SystemMenu;
use think\admin\model\SystemNode;


/**
 * 公司角色
 * @package app\admin\controller
 * @author wangqinghui
 * @DateTime 2024-09-11 13:58:44
 */
class Role extends Controller
{

    /**
     * 公司角色列表
     * @auth true
     * @menu true
     * @author Lihongqi
     * @DateTime 2024-09-11 14:56:28
     * @return void
     */
    public function index ()
    {
        SystemAuth::mQuery()->layTable(function () {
            $this->title = '角色列表';

        }, function (QueryHelper $query) {

            $query->checkAccount()->where('utype', 'shop');
            // 数据列表搜索过滤
            $query->like('name')->equal('status')->dateBetween('create_at');
            //$query->order('sort desc, id asc');
        });

    }
    protected function _index_page_filter (&$data)
    {
        foreach ($data as $item) {
            
        }
    }

    /**
     * 修改权限状态
     * @auth true
     */
    public function state()
    {
        SystemAuth::mSave($this->_vali([
            'status.in:0,1'  => '状态值范围异常！',
            'status.require' => '状态值不能为空！',
        ]));
    }

    /**
     * 删除系统权限
     * @auth true
     */
    public function remove()
    {
        SystemAuth::mDelete();
    }


    /**
     * 添加系统权限
     * @auth true
     */
    public function add()
    {
        SystemAuth::mForm('form');
    }

    /**
     * 编辑系统权限
     * @auth true
     */
    public function edit()
    {
        SystemAuth::mForm('form');
    }

    /**
     * 表单后置数据处理
     * @param array $data
     */
    protected function _form_filter(array $data)
    {
        if ($this->request->isGet()) {

            $this->account_arr = AccountModel::mk()->where('1=1')->column('title', 'id');
            $this->title = empty($data['title']) ? "添加访问授权" : "编辑【{$data['title']}】授权";

        } elseif ($this->request->post('action') === 'json') {

            // 找到对应的 菜单节点
            $nodes = SystemNode::mk()->where('auth', 3)->column('node');
            // 找到选中的节点
            $checks = empty($data['id']) ? [] : SystemNode::mk()->where(['auth' => $data['id']])->column('node');
            // 如果是上级权限中的节点
            MenuNodesModel::mk()->whereIn("node", $nodes)->select()->each(function ($item) use (&$menuNodes, $checks, &$onlyNodes){

                $item->checked = in_array($item->node, $checks) ;
                // 当前节点属于哪个菜单
                $menuNodes[$item->menu_id][] = $item->toArray();
                // 记录数据节点的数组
                $onlyNodes[] = $item->node;
            });

            // 数组求差集  获得所有菜单节点
            $nodes = array_diff($nodes, $onlyNodes);
            // 根据菜节点  找到菜单详细信息
            $menus_nodes = SystemMenu::mk()->field('id,pid as pnode,node,title')->whereIn('node', $nodes)->where(['status' => 1])->order('sort desc,id asc')->select();
            // 所有带节点的菜单的上级
            $menus_parent = SystemMenu::mk()->field('id,pid as pnode,node,title')->whereIn('id', $menus_nodes->column('pnode'))->where(['status' => 1])->order('sort desc,id asc')->select();

            // 找到所有的模块
            $menus_moduls = SystemMenu::mk()->field('id,pid as pnode,node,title')->whereIn('id', $menus_parent->column('pnode'))->where(['status' => 1])->order('sort desc,id asc')->select();


            // 合并 所有数据
            $menus = array_merge($menus_nodes->toArray(), $menus_parent->toArray(), $menus_moduls->toArray());

            $parent_checked = [];

            foreach ($menus as  &$item) {

                $item['checked'] = in_array($item['node'], $checks);

                if ($item['checked']) { // 记录上级id

                    $parent_checked[] = $item['pnode'];
                }

                if ( isset($menuNodes[$item['id']]) ) {

                    $_sub_ = array_merge([$item], $menuNodes[$item['id']]);
                    $item['_sub_'] = $_sub_;
                }
            }

            $this->checkParentStatus($menus, $parent_checked);


            $data = DataExtend::arr2tree($menus, 'id', 'pnode', "_sub_");

            $this->success('获取权限节点成功！', $data);

        } elseif (empty($data['nodes'])) {
            $this->error('未配置功能节点！');
        }
    }

    /**
     * 节点更新处理
     * @param boolean $state
     * @param array $post
     * @return void
     */
    protected function _form_result(bool $state, array $post)
    {
        if ($state && $this->request->post('action') === 'save') {

            [$map, $data] = [['auth' => $post['id']], []];
            $post['nodes'] = array_unique($post['nodes']);

            foreach ($post['nodes'] ?? [] as $node) $data[] = $map + ['node' => $node];
            SystemNode::mk()->where($map)->delete();
            count($data) > 0 && SystemNode::mk()->insertAll($data);
            sysoplog('系统权限管理', "配置系统权限[{$map['auth']}]授权成功");
            $this->success('权限修改成功！', 'javascript:history.back()');
        }
    }



    protected function checkParentStatus(&$data, $ids)
    {
        $parent_ids = [];
        foreach ($data as &$item) {

            if ( in_array($item['id'], $ids) ) {
                $item['checked'] = true;
                $parent_ids[] = $item['pnode'];
            }
        }

        if ( !empty($parent_ids) ) {
            $this->checkParentStatus($data, $parent_ids);
        }

    }

}